package cn.tedu.account.service;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;



    @Transactional //启动seata事务
    @Override
    public void decrease(Long userId, BigDecimal money) {
        Account a = accountMapper.selectByUserId(userId);
        /*
        BigDecimal a   BigDecimal b
        a.compareTo(b)
            返回值
                正数，表示a大
                负数，表示a小
                0，表示相同
         */
        if (a.getResidue().compareTo(money) < 0) {
            throw new RuntimeException("可用金额不足");
        }
        accountMapper.decrease(userId, money);

//        if (Math.random() < 0.5) {
//            throw new RuntimeException("模拟异常");
//        }
    }
}
